import * as React from'react'
import { MessageType } from '../../../src/utils/MessageHandler'
import ChatInputBox from '../components/ChatInputBox'
import { useEvent } from 'react-use'
import { HighlightjsParam, LocalChunkMessage, LocalModelMessage, Task } from '../../../src/store/types'
import { vscode } from '../utils/vscode'
import ChatBox from '../components/ChatBox'
import { useParams } from 'react-router'
import { ChunkMessage } from '../../../src/model/types'

export default React.memo(function() {

	const [ messages, setMessages ] = React.useState<LocalModelMessage[]>([])
	console.log(messages)
	const params = useParams()
	const taskId = params.taskId
	const [messageChunks, setMessageChunks ] = React.useState<ChunkMessage[]>([])
	const [localChunk, setLocalChunk ] = React.useState<LocalChunkMessage>()
	const [highlightjs, setHighlightjs] = React.useState<HighlightjsParam>()

	const handleMessage = React.useCallback((e: MessageEvent) => {
		const message = e.data
		console.log('ChatPage收到消息', message)	
		if(message.type === MessageType.receivedLLMMessage) {
			console.log('ChatPage收到LLM消息', message)
			const newChunk = message.data as LocalChunkMessage;
			if(newChunk.index === 0) {
				setMessageChunks([newChunk.chunk])
				return;
			}
			setMessageChunks(prev => [...prev, newChunk.chunk])
			setLocalChunk(newChunk)
		}
		if(message.type === MessageType.getTask) {
			const task: Task = message.data as Task;
			setMessages(task.messages ?? [])

			if(messageChunks.length > 0 && task.messages?.find((item) => item.msgId == localChunk?.msgId)) {
				setLocalChunk(undefined)
				setMessageChunks([])
				return;
			}
		}
		if(message.type === MessageType.getHighlightjs) {
			setHighlightjs(message.data as HighlightjsParam)
		}
	}, [localChunk?.msgId, messageChunks.length])

	useEvent('message', handleMessage)

	React.useEffect(() => {
		console.log('ChatPage')
		vscode.postMessage({type: MessageType.getTask,data: { taskId }})
		vscode.postMessage({type: MessageType.getHighlightjs })
		return () => {
			console.log('ChatPage卸载')
		}
	}, [taskId])

	return (
		<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
			<ChatBox messages={messages} chunks={messageChunks} highlightjs={highlightjs} />
			<div style={{height: '120px', padding: '0px 20px' }}>
				<ChatInputBox />
			</div>
		</div>
	)
})